﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class GameManager : MonoBehaviour
{

    public static GameManager Instance;
    public PlayerPawn playerPawn;
    public DataObject data;

    public UnityEvent eventOnMove;
    public UnityEvent eventOnFail;
    public UnityEvent eventOnSuccess;
    
    public bool isGameOver = false;
    
    public TileContainer tileContainer;

    public GameObject uiCanvas;

    public int score = 0;
    
    public PlayerBuilding playerBuildingTemplet;

    // Start is called before the first frame update
    void Awake()
    {
        Instance = this;
        tileContainer = FindObjectOfType<TileContainer>();
        tileContainer.Init();

        uiCanvas = GameObject.Find("Canvas");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            uiCanvas.transform.Find("WelcomePanel").gameObject.SetActive(false);
        }
    }

    public List<T> GetContentList<T>() where T : BaseContent
    {
        return tileContainer.GetContentList<T>();
    }

    public void OnMove()
    {
        eventOnMove.Invoke();
    }
    public void OnFail()
    {
        Debug.Log("Game Fail!!!");
        isGameOver = true;
        
        uiCanvas.transform.Find("GameOverPanel").gameObject.SetActive(true);
        uiCanvas.transform.Find("Restart").gameObject.SetActive(true);

        eventOnFail.Invoke();
    }

    public void OnSuccess()
    {
        Debug.Log("Game Success!!!");
        isGameOver = true;

        Invoke("OnPostSuccess", 3f);
    }
    
    public void OnPostSuccess()
    {
        uiCanvas.transform.Find("GameSuccessPanel").gameObject.SetActive(true);
        uiCanvas.transform.Find("Restart").gameObject.SetActive(true);

        eventOnSuccess.Invoke();
    }

    public void BindToOnMove(UnityAction call)
    {
        eventOnMove.AddListener(call);
    }
    public void BindToOnFail(UnityAction call)
    {
        eventOnFail.AddListener(call);
    }
    public void BindToOnSuccess(UnityAction call)
    {
        eventOnSuccess.AddListener(call);
    }

    public void OnDeliver()
    {
        score += GetData().scorePerDelivery;
    }
    
    public bool IsScoreEnough()
    {
        return score >= GetData().successScore;
    }

    public static DataObject GetData()
    {
        return Instance.data;
    }
}
